package com.meiyuetao.myt.partner.web.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;
import lab.s2jh.core.web.view.OperationResult;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meiyuetao.myt.core.constant.VoucherStateEnum;
import com.meiyuetao.myt.core.constant.VoucherTypeEnum;
import com.meiyuetao.myt.core.service.VoucherNumGenerateService;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.finance.entity.AccountSubject;
import com.meiyuetao.myt.finance.service.AccountSubjectService;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.service.CommodityService;
import com.meiyuetao.myt.partner.entity.DistributeDelivery;
import com.meiyuetao.myt.partner.entity.DistributeDelivery.DistributeDeliveryStatusEnum;
import com.meiyuetao.myt.partner.entity.DistributeDeliveryDetail;
import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.partner.service.DistributeDeliveryService;
import com.meiyuetao.myt.partner.service.PartnerService;

@MetaData("SaleDeliveryController")
public class DistributeDeliveryController extends MytBaseController<DistributeDelivery, Long> {

    @Autowired
    private DistributeDeliveryService distributeDeliveryService;
    @Autowired
    private VoucherNumGenerateService voucherNumGenerateService;
    @Autowired
    private AccountSubjectService accountSubjectService;
    @Autowired
    private PartnerService partnerService;
    @Autowired
    private CommodityService commodityService;

    // private StockInOutService stockInOutService;

    @Override
    protected BaseService<DistributeDelivery, Long> getEntityService() {
        return distributeDeliveryService;
    }

    @Override
    protected void checkEntityAclPermission(DistributeDelivery entity) {

    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "distributeDeliveryDetails");
    }

    @MetaData("红冲单据")
    public HttpHeaders chargeAgainst() {
        distributeDeliveryService.chargeAgainst(bindingEntity);
        setModel(OperationResult.buildSuccessResult("红冲完成"));
        return buildDefaultHttpHeaders();
    }

    @Override
    public String isDisallowUpdate() {
        if (VoucherStateEnum.REDW.equals(bindingEntity.getVoucherState())) {
            return "已红冲的不能修改";
        }
        if (bindingEntity.isNotNew() && bindingEntity.getDeliveryTime() != null) {
            return "已快递发货，不允许再修改";
        }
        return null;
    }

    public String isDisallowChargeAgainst() {

        if (VoucherStateEnum.REDW.equals(bindingEntity.getVoucherState())) {
            return "已红冲";
        }
        if (bindingEntity.isNotNew() && bindingEntity.getDeliveryTime() != null) {
            return "已发货的不能红冲";
        }
        return null;
    }

    public void prepareBpmNew() {
        bindingEntity = new DistributeDelivery();
        bindingEntity.setVoucher(voucherNumGenerateService.getVoucherNumByType(VoucherTypeEnum.PH));
        bindingEntity.setVoucherDate(new Date());
        bindingEntity.setVoucherUser(getLogonUser());
        bindingEntity.setVoucherDepartment(getLogonUser().getDepartment());
    }

    @MetaData("创建初始化")
    public HttpHeaders bpmNew() {
        return buildDefaultHttpHeaders("bpmInput");
    }

    @MetaData("代理商配货单保存")
    public HttpHeaders bpmSave() {
        Map<String, Object> variables = Maps.newHashMap();
        String submitToAudit = this.getParameter("submitToAudit");
        if (BooleanUtils.toBoolean(submitToAudit)) {
            bindingEntity.setLastOperationSummary(bindingEntity.buildLastOperationSummary("提交"));
            bindingEntity.setSubmitDate(new Date());
            bindingEntity.setDistributeDeliveryStatus(DistributeDeliveryStatusEnum.S20SUBMITTED);
        }

        List<DistributeDeliveryDetail> details = bindingEntity.getDistributeDeliveryDetails();

        if (StringUtils.isBlank(bindingEntity.getTitle())) {
            Commodity commodity = commodityService.findOne(details.get(0).getCommodity().getId());
            String commodityTitle = commodity.getTitle();
            commodityTitle = StringUtils.substring(commodityTitle, 0, 30);
            bindingEntity.setTitle(commodityTitle + "...等" + details.size() + "项商品");
        }

        List<Long> commodityIds = new ArrayList<Long>();
        for (DistributeDeliveryDetail detail : details) {
            detail.setDistributeDelivery(bindingEntity);
            commodityIds.add(detail.getCommodity().getId());
        }
        Partner partner = bindingEntity.getAgentPartner();
        if (partner != null) {
            Long partnerId = partner.getId();
            partner = partnerService.findOne(partnerId);
            /*
             * 校验所选商品是否属于同一代理商父子路径
             */
            // 检测本次提交表单没有用户已confirm确认标识，则进行相关预警校验检查
            if (postNotConfirmedByUser()) {
                List<String> messages = Lists.newArrayList();
                if (!partnerService.checkCommodityAgentPartners(commodityIds, partner)) {// 不是同一分销商提示用户
                    messages.add("当前配货单所有商品不属于同一个代理系列，会导致无法合理的指派分销商");
                }
                if (messages.size() > 0) {
                    setModel(OperationResult.buildConfirmResult("配货单数据处理警告", messages));
                    // 直接返回使用户进行Confirm确认
                    return buildDefaultHttpHeaders();
                }
            }
        }
        if (StringUtils.isNotBlank(getParameter("payedAmount")) && StringUtils.isBlank(getParameter("accountSubject.id"))) {
            Validation.isTrue(false, "如有收款金额则必须选取收款账户");
        }

        if (bindingEntity.isNew()) {
            // 销售单页面如果没有输入“关联订单号”，则提交处理逻辑中兼容处理取凭证号赋值给“关联订单号”
            if (StringUtils.isBlank(bindingEntity.getReferenceVoucher())) {
                bindingEntity.setReferenceVoucher(bindingEntity.getVoucher());
            }
            distributeDeliveryService.bpmCreate(bindingEntity, variables);
            setModel(OperationResult.buildSuccessResult("代理商配货单创建完成，并同步启动处理流程", bindingEntity));
        } else {
            distributeDeliveryService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
            setModel(OperationResult.buildSuccessResult("代理商配货单任务提交完成", bindingEntity));
        }
        return buildDefaultHttpHeaders();

    }

    @MetaData("一线审核")
    public HttpHeaders bpmLevel1Audit() {
        Map<String, Object> variables = Maps.newHashMap();
        variables.put("auditLevel1Time", new Date());
        variables.put("auditLevel1User", AuthContextHolder.getAuthUserPin());
        Boolean auditLevel1Pass = new Boolean(getRequiredParameter("auditLevel1Pass"));
        variables.put("auditLevel1Pass", auditLevel1Pass);
        variables.put("auditLevel1Explain", getParameter("auditLevel1Explain"));
        bindingEntity.setLastOperationSummary(bindingEntity.buildLastOperationSummary("审核"));
        bindingEntity.setAuditBy(AuthContextHolder.getAuthUserPin());
        if (!auditLevel1Pass) {
            bindingEntity.setSubmitDate(null);
            bindingEntity.setDistributeDeliveryStatus(DistributeDeliveryStatusEnum.S10DRAFT);
        }
        distributeDeliveryService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("代理商配货单一线审核完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @MetaData("录入发货信息")
    public HttpHeaders shipmentsInfo() {
        Map<String, Object> variables = Maps.newHashMap();
        bindingEntity.setDistributeDeliveryStatus(DistributeDeliveryStatusEnum.S40DELIVERIED);
        distributeDeliveryService.bpmUpdate(bindingEntity, this.getRequiredParameter("taskId"), variables);
        setModel(OperationResult.buildSuccessResult("录入发货信息完成", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        distributeDeliveryService.save(bindingEntity);
        setModel(OperationResult.buildSuccessResult("数据保存成功", bindingEntity));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @MetaData("行项数据")
    public HttpHeaders details() {
        List<DistributeDeliveryDetail> details = bindingEntity.getDistributeDeliveryDetails();
        if (BooleanUtils.toBoolean(getParameter("clone"))) {
            for (DistributeDeliveryDetail detail : details) {
                detail.resetCommonProperties();
            }
        }
        setModel(buildPageResultFromList(details));
        return buildDefaultHttpHeaders();
    }

    @MetaData(value = "付款会计科目数据")
    public Map<Long, String> getPaymentAccountSubjects() {
        Map<Long, String> datas = Maps.newLinkedHashMap();
        Iterable<AccountSubject> items = accountSubjectService.findPaymentAccountSubjects();
        for (AccountSubject item : items) {
            datas.put(item.getId(), item.getDisplay());
        }
        return datas;
    }
}